package com.medicinemanager.ui;

import com.example.medicinemanager.R;
import com.medicinemanager.business.LoginConfigure;
import com.medicinemanager.business.ShowMessage;
import com.medicinemanager.control.DoubleClickExit;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends BaseActivity{

	private final String APPNAME = "MEDICINEMANAGER";
	private DoubleClickExit mDoubleClickExit = null;
	private EditText mEditTextAccount = null;
	private EditText mEditTextPassword = null;
	private SharedPreferences mUserLoginInfor = null;
	private Button mBtnLogin = null;
	private OnClickListener mOnClickListener = null;
	private LoginConfigure mLoginConfigure = null;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		
		initEditText();
		initButton();
		initAction();
	}
	
	private void initEditText(){
		mUserLoginInfor = this.getSharedPreferences(APPNAME, Context.MODE_WORLD_READABLE);
		mEditTextAccount = (EditText) findViewById(R.id.ed_account);
		mEditTextPassword = (EditText) findViewById(R.id.ed_password);
		
		mEditTextAccount.setText(mUserLoginInfor.getString("account", ""));
		mEditTextPassword.setText(mUserLoginInfor.getString("password", ""));
	}
	
	private void initButton(){
		mOnClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				mUserLoginInfor.edit().putString("account", mEditTextAccount.getText().toString()).commit();
				mUserLoginInfor.edit().putString("password", mEditTextPassword.getText().toString()).commit();
				if(mLoginConfigure.validAccount(mEditTextAccount.getText().toString(), mEditTextPassword.getText().toString())){
					gotoAhead();
				}else{
					ShowMessage.showToast(getApplicationContext(), "accout or password error");
				}
			}
		};
		
		mBtnLogin = (Button) findViewById(R.id.btn_login);
		mBtnLogin.setOnClickListener(mOnClickListener);
	}
	
	private void initAction(){
		mDoubleClickExit = new DoubleClickExit(LoginActivity.this);
		mLoginConfigure = new LoginConfigure(LoginActivity.this);
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event){
		return super.onKeyDown(keyCode, event);
	}
	
	public void gotoBack() {
		mDoubleClickExit.exitApp();
	}

	public void gotoAhead() {
		Intent intent = new Intent();
		intent.setClass(LoginActivity.this, MainActivity.class);
		LoginActivity.this.startActivity(intent);
	}

}
